﻿using System;
using System.Linq;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Administration.Web.Services
{
    public class LicenseService
    {
        public EntitlementsDatabase Db { get; private set; }

        public LicenseService()
        {
            Db = new EntitlementsDatabase("EntitlementsDatabase");
        }

        public LicenseService(EntitlementsDatabase db)
        {
            Db = db;
        }

        public IQueryable<License> GetLicenses(int page = 1, int pageSize = 0)
        {
            if (page == 1 && pageSize == 0)
                return Db.Licenses.OrderBy(i => i.Name);
            return Db.Licenses.OrderBy(i => i.Name).Skip((page - 1) * pageSize).Take(pageSize);
        }

        public License GetLicense(Guid id)
        {
            return Db.Licenses.Find(id);
        }

        public License GetLicense(string name)
        {
            return Db.Licenses.FirstOrDefault(f => f.Name == name);
        }

        public License CreateLicense(License license)
        {
            Db.Licenses.Add(license);
            Db.SaveChanges();
            return license;
        }
    }
}